<template>
  <view class="scan_code_wrap">
    <block>
      <uni-section
        class="mb-10"
        title="商品条码（手动输入或使用扫码枪）  "
        type="line"
      ></uni-section>
      <view class="form-item">
        <uni-easyinput
          v-model="value"
          :focus="isFocus"
          placeholder="商品条码（手动输入或使用扫码枪）"
          @confirm="confirmFn"
        ></uni-easyinput>
      </view>
    </block>

    <uni-card
      spacing="10px"
      v-if="goods.length > 0"
      v-for="(item, index) in goods"
      :key="index"
    >
      <image slot="cover" style="width: 100%" :src="item.photos[0].url"></image>
      <text class="uni-body">{{ item.name }}</text>
    </uni-card>
  </view>
</template>

<script>
import CryptoJS from "crypto-js";
import { buildElmGetGoodsUrl, buildSaasGetGoodsUrl } from "./utils";

function signMethod({
  cmd,
  encrypt,
  secret,
  source,
  timestamp,
  body,
  ticket,
  version,
}) {
  const signData = {};

  // 原始参数
  signData["cmd"] = cmd;
  signData["encrypt"] = encrypt;
  signData["secret"] = secret;
  signData["source"] = source;
  signData["ticket"] = ticket;
  signData["timestamp"] = timestamp; // 当前秒级时间戳
  signData["version"] = version;
  signData["body"] = body;

  // 对参数对象的键进行排序
  const sortedKeys = Object.keys(signData).sort();

  // 拼接参数字符串
  let tmp = [];
  sortedKeys.forEach((key) => {
    tmp.push(`${key}=${signData[key]}`);
  });

  // 用&拼接成字符串
  const strSign = tmp.join("&");

  // 计算MD5签名并转换为大写
  const sign = CryptoJS.MD5(strSign).toString().toUpperCase();

  return sign;
}

function request(options) {
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    });
  });
}

export default {
  components: {},
  onLoad() {},
  data() {
    return {
      value: "",
      type: "text",
      border: true,
      isFocus: false,
      goods: [],
    };
  },
  methods: {
    // 重置输入框的聚焦状态
    resetInputFocus() {
      this.isFocus = false;
      this.$nextTick(() => {
        this.value = "";
        this.isFocus = true;
        uni.hideLoading();
      });
    },
    async confirmFn(e) {
      const _app = this;

      // 商品自定义库存id
      let goodCustomSkuId = 0;
      uni.showLoading({
        title: "减少库存中...",
        mask: true,
      });

      const ticket = "5B50C1E9-A366-445D-9057-02E30B68D23A";

      const shopId = uni.getStorageSync("shopId"); //523013117

      if (!shopId) {
        return uni.showToast({
          title: "请先去个人资料页填写门店id",
          icon: "none",
          duration: 2000,
        });
      }

      try {
        const { data: _goodsInfo } = await request({
          url: buildElmGetGoodsUrl({
            shopId,
            cmd: "sku.list",
            upc: e,
            ticket,
            timestamp: Math.floor(Date.now() / 1000),
          }),
        });

        const { data: elemeGoodInfo } = _goodsInfo?.body || {};

        // 如果在饿了么零售平台查不到该商品
        if (elemeGoodInfo?.total === 0) {
          uni.showModal({
            title: "提示",
            content: "没有找到该商品",
            success: function (res) {
              if (res.confirm) {
                _app.resetInputFocus();
              } else if (res.cancel) {
              }
            },
            showCancel: false,
          });

          return;
        }

        // 如果在饿了么零售平台查到该商品
        if (elemeGoodInfo?.total > 0) {
          // 获取其自定义商品id
          goodCustomSkuId = elemeGoodInfo?.list[0]?.custom_sku_id;
        }
      } catch (error) {
        console.log("error", error);
      }

      try {
        //3001854128046
        const { data: saasGoodsInfo } = await request({
          url: buildSaasGetGoodsUrl({
            cmd: "saas.goods.store.query.batch",
            skuId: goodCustomSkuId,
            timestamp: Math.floor(Date.now() / 1000),
          }),
        });

        const _spuCode =
          saasGoodsInfo?.body?.data?.channelGoodsSyncReqList?.[0]?.spu_code;

          console.log('_spuCode',_spuCode);
          
      } catch (error) {
        console.log("error", error);
      }

      return;

      uni.request({
        url: `https://api-be.ele.me/?body=%7B%22shop_id%22%3A%22${shopId}%22%2C%22upc%22%3A%22${e}%22%7D&cmd=sku.list&encrypt=${encrypt}&sign=${sign}&source=${source}&ticket=${skuticket}&timestamp=1733424716&version=3`,

        method: "POST",
        success: (_sku_list) => {
          if (_sku_list.data.body.errno !== 0) {
            uni.showToast({
              title: _sku_list.data.body.error,
              icon: "none",
              duration: 2000,
            });
            this.isFocus = false;
            this.$nextTick(() => {
              this.value = "";
              this.isFocus = true;
              uni.hideLoading();
            });

            return;
          }

          if (_sku_list.data.body.data.total === 0) {
            uni.showToast({
              title: "没有找到商品",
              icon: "none",
              duration: 2000,
            });
            this.isFocus = false;
            this.$nextTick(() => {
              this.value = "";
              this.isFocus = true;
              uni.hideLoading();
            });
          }

          const _goodsInfoNum = _sku_list.data.body.data.list[0].left_num;

          const good_id = _sku_list.data.body.data.list[0].item_id;

          const _key = signMethod({
            cmd,
            encrypt,
            body: `{"shop_id":"${shopId}","upc_stocks":"${e}:${
              _goodsInfoNum - 1
            };"}`,
            secret,
            source,
            ticket,
            timestamp,
            version,
          });

          uni.request({
            // url: `https://api-be.ele.me/?body=%7B%22shop_id%22%3A%22${shopId}%22%2C%22upc_stocks%22%3A%22${e}%3A${
            //   _goodsInfoNum - 1
            // }%3B%22%7D&cmd=${cmd}&encrypt=${encrypt}&sign=${_key}&source=${source}&ticket=${ticket}&timestamp=${timestamp}&version=${version}`,
            url: `https://api-be.ele.me/?body=%7B%22merchant_code%22%3A%22${merchant_code}%22%2C%22sku_list%22%3A%5B%7B%22quantity%22%3A3%${2}C%22sku_code%22%3A%22${good_id}%22%7D%5D%2C%22erp_store_code%22%3A%22${erp_store_code}%22%7D&cmd=saas.sku.stock.update.batch&encrypt=${encrypt}&sign=${_key}&source=${source}&ticket=359EDD67-8D06-4B05-AEFA-0DD3A59BC9B5&timestamp=1734009574&version=3`,
            method: "POST",
            // data: {
            //   shop_id: shopId,
            //   upc_stocks: `${e}:${_goodsInfoNum - 1};`,
            // },
            success: (res) => {
              console.log("resresresres", res);

              if (res.data.body.errno !== 0) {
                uni.showToast({
                  title: `库存减少失败`,
                  icon: "none",
                  duration: 2000,
                });

                this.isFocus = false;
                this.$nextTick(() => {
                  this.value = "";
                  this.isFocus = true;
                  uni.hideLoading();
                });

                return;
              }

              _sku_list.data.body.data.list.forEach((_item) => {
                // this.goods.push(_item);
                /* 添加到第一位 */
                this.goods.unshift(_item);
              });

              this.isFocus = false;
              this.$nextTick(() => {
                this.value = "";
                this.isFocus = true;
                uni.hideLoading();
              });
            },
          });
        },
      });
    },
  },
  // 挂载后
  mounted() {
    this.$nextTick(() => {
      this.isFocus = true;
    });
  },
};
</script>

<style lang="scss">
// @import "./list.scss";

.scan_code_wrap {
  background: #fff;
  height: 100vh;
}

.container {
  overflow: hidden;
}

.custom-cover {
  flex: 1;
  flex-direction: row;
  position: relative;
}

.cover-content {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background-color: rgba($color: #000000, $alpha: 0.4);
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-left: 15px;
  font-size: 14px;
  color: #fff;
}

.card-actions {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  align-items: center;
  height: 45px;
  border-top: 1px #eee solid;
}
.card-actions-item {
  display: flex;
  flex-direction: row;
  align-items: center;
}
.card-actions-item-text {
  font-size: 12px;
  color: #666;
  margin-left: 5px;
}
.cover-image {
  flex: 1;
  height: 150px;
}
.no-border {
  border-width: 0;
}

.form-item {
  padding-left: 30rpx;
  padding-right: 30rpx;
}
</style>

<style></style>
